package com.hwadee.ems.util;

import java.time.ZoneOffset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import jakarta.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author EnosElinsa
 * @since 2024/06/19
 */
@Component
public class RedisIdWorker {

    private static final long BEGIN_TIMESTAMP = 1704067200; 
    private static final int SEQUENCE_BITS = 32;

    @Resource
    private StringRedisTemplate srt;
    
    @SuppressWarnings("null")
    public long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long currentTimestamp = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = currentTimestamp - BEGIN_TIMESTAMP;

        // 2. 生成序列号
        // 2.1 获取当前日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2 自增长
        Long sequence = srt.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        // 3. 拼接并返回
        return timestamp << SEQUENCE_BITS | sequence;
    }

}

